from django.db import models
from datetime import datetime

# Create your models here.

class Server(models.Model):
    name = models.CharField(max_length=250)
    
    class Meta:
        ordering = ['name']
    #end class
    
    def __unicode__(self):
        return "%s server: %i towns, %i IP addresses" % (self.name, len(Town.objects.filter(server=self)), len(IPaddress.objects.filter(server=self)))
    #end def
#end class

class IPaddress(models.Model):
    IP = models.IPAddressField()
    port = models.IntegerField(default=11020)
    server = models.ForeignKey(Server)
    
    class Meta:
        ordering = ['IP', 'port']
        verbose_name = 'IP Address'
        verbose_name_plural = 'IP Addresses'
    #end class
    
    def __unicode__(self):
        return "%s:%i (IP for %s)" % (self.IP, self.port, self.server.name)
    #end def
#end class
    
class Town(models.Model):
    name = models.CharField(max_length=250)
    server = models.ForeignKey(Server)
    position = models.IntegerField()
    
    class Meta:
        ordering = ['position']
    #end class
    
    def __unicode__(self):
        return "%s (%s server) (%i items)" % (self.name, self.server.name, len(Item.objects.filter(selling_town=self)))
    #end def
#end class

class Item(models.Model):
    name = models.CharField(max_length=250)
    profit = models.IntegerField(default=0)
    position = models.IntegerField()
    selling_town = models.ForeignKey(Town, related_name='selling')
    destination_town = models.ForeignKey(Town, related_name='destination')
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    
    class Meta:
        ordering = ['position']
    #end class
    
    def __unicode__(self):
        return "%s for %i profit, bought from %s, sold to %s" % (self.name, self.profit, self.selling_town.__unicode__(), self.destination_town.__unicode__())
    #end def
#end class